//
//  SpringboardController.m
//  YuchBox
//
//  Created by Ivan on 11-9-28.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "SpringboardController.h"
#import "YuchBoxAppDelegate.h"
#import "Account.h"

typedef enum {
    ConnectStateNone         = -1,
    ConnectStateDisconnet    = 0,
    ConnectStateConneting,
    ConnectStateConneted,
    ConnectStateRetry,
} ConnectState;

enum view_tag {
    CONNECT_BUTTON_TAG  = 0,
};

#define ANIMATION_INTERVAL      0.7f

@implementation SpringboardController

@synthesize host        = _host;
@synthesize port        = _port;
@synthesize password    = _password;
//@synthesize connectView = _connectView;
@synthesize button      = _button;
@synthesize stateLabel  = _stateLabel;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.view.frame     = CGRectMake(0, 20, 320, 460);

    }
    return self;
}

- (void)dealloc
{
//    [_stateImages release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)myInit
{
    _stateString = [[NSArray alloc] initWithObjects:
                    @"连接已断开", 
                    @"连接中...", 
                    @"已连接，点击断开连接", 
                    @"连接失败，重新连接中...", nil];
    _animationState     = ConnectStateDisconnet;
    _state              = ConnectStateNone;
    _connectRetryTimes  = 0;
    _stateImages = [[NSArray alloc] initWithObjects:[UIImage imageNamed:@"spring_state_disconnect"],
                    [UIImage imageNamed:@"spring_state_connecting"],
                    [UIImage imageNamed:@"spring_state_connected"], nil];
}

- (void)setState:(ConnectState)state
{
    if (_state != state) {
        [_button setBackgroundImage:[_stateImages objectAtIndex:state] forState:UIControlStateNormal];
        _state = state;
        
        _stateLabel.text = [_stateString objectAtIndex:state];
        
        switch (_state) {
            case ConnectStateDisconnet: {
                [DATA_SOURCE logout];
                [self stopConnectAnimationTimer];
                
                [[YuchBoxAppDelegate shareStateViewer] setStateEvent:StateEventOffline];

                break;
            }
            case ConnectStateConneting: {
                [self startConnectAnimationTimer];
                [DATA_SOURCE.configuration setHostname:_host.text];
                [DATA_SOURCE.configuration setPort:[_port.text intValue]];
                [DATA_SOURCE.configuration setPasswordKey:_password.text];
                [DATA_SOURCE connectAndLogin];
                break;
            }
            case ConnectStateConneted: {
                [self stopConnectAnimationTimer];
                [[YuchBoxAppDelegate shareStateViewer] setStateEvent:StateEventOnline];
                break;
            }
            default:
                break;
        }
    }
}
//
//- (void)setStateImage:(ConnectState)state
//{
//    [_button setBackgroundImage:[_stateImages objectAtIndex:state] forState:UIControlStateNormal];
//}

- (void)touchUpInside:(UIButton *)button
{
    [_currentEditTextField resignFirstResponder];
    _timeInterval = [[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970] - _timeInterval;
    
    // for easter eggs
    if (_timeInterval > 1.2f) {
        [[YuchBoxAppDelegate shareAppDelegate] setSubViewTop:WindowViewTagForNavigationBar];
        return;
    }
    switch (_state) {
        case ConnectStateDisconnet:
            [self setState:ConnectStateConneting];
            break;
        case ConnectStateConneting:
            [self setState:ConnectStateDisconnet];
            break;     
        case ConnectStateConneted:
            [self setState:ConnectStateDisconnet];
            break;
        default:
            break;
    }
}


- (void)touchDown:(UIButton *)button
{
//    if (_state == ConnectStateConneted) {
    _timeInterval = [[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970];
//    }
    
}

- (void)touchUpOutside:(UIButton *)button
{
    
}

- (void)connectAnimation:(id)sender
{
    if (ConnectStateConneting == _animationState) {
        _animationState = ConnectStateDisconnet;
        [_button setBackgroundImage:[_stateImages objectAtIndex:ConnectStateDisconnet] forState:UIControlStateNormal];
    } else if (ConnectStateDisconnet == _animationState) {
        _animationState = ConnectStateConneting;
        [_button setBackgroundImage:[_stateImages objectAtIndex:ConnectStateConneting] forState:UIControlStateNormal];
    }
}

- (void)startConnectAnimationTimer
{
    _connectAnimationTimer = [NSTimer scheduledTimerWithTimeInterval:ANIMATION_INTERVAL target:self selector:@selector(connectAnimation:) userInfo:nil repeats:YES];
}

- (void)stopConnectAnimationTimer
{
    if (nil == _connectAnimationTimer || [_connectAnimationTimer isValid]) {
        [_connectAnimationTimer invalidate];
        _connectAnimationTimer = nil;
    }
}

#pragma mark - 
#pragma mark View lifecycle
- (void)viewDidAppear:(BOOL)animated
{
    //TODO: init the login or relogin things here
    //[self initSqliteDb];
    
    //TEST
    //[super viewDidAppear:animated];
    
    NSLog(@"DidAppear\n");
}

- (void)viewWillDisappear:(BOOL)animated
{
     NSLog(@"WillDisappear\n");
}

- (void)viewDidDisappear:(BOOL)animated
{
    NSLog(@"DidDisappear\n");
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    [self myInit];
    
    [self setState:ConnectStateDisconnet];// setStateImage:ConnectStateDisconnet];
    
    _button.adjustsImageWhenHighlighted = NO;

    [_button addTarget:self action:@selector(touchDown:)      forControlEvents:UIControlEventTouchDown];
    [_button addTarget:self action:@selector(touchUpInside:)  forControlEvents:UIControlEventTouchUpInside];
    [_button addTarget:self action:@selector(touchUpOutside:) forControlEvents:UIControlEventTouchUpOutside];

    //
    self.host.keyboardType  = UIKeyboardTypeURL;
    self.host.returnKeyType = UIReturnKeyDone;
    self.host.delegate      = self;
    
//    self.host.text = @"45562.yuchberry.info";
    self.port.keyboardType  = UIKeyboardTypeNumberPad;
    self.port.returnKeyType = UIReturnKeyDone;
    self.port.delegate      = self;

//    self.port.text = @"8743";
    //
    self.password.keyboardType  = UIKeyboardTypeDefault;
    self.password.returnKeyType = UIReturnKeyDone;
    self.password.delegate      = self;
#define MAX_SESSION_TIME_OUT    3600 * 24 * 1   
    Account *lastLoginAccount = [[Account alloc] init];
    [Account getLastLoginAccount:IVAN_DB account:lastLoginAccount withTimeoutInterval:(UInt64)MAX_SESSION_TIME_OUT];

    if (0 != lastLoginAccount.uid) {
        self.host.text = lastLoginAccount.host;
        self.port.text = [NSString stringWithFormat:@"%d", lastLoginAccount.port];
        self.password.text = lastLoginAccount.password;
        
//        [self touchUpInside:nil];
    } else {
        
    }
    [lastLoginAccount release];
    _stateLabel.textAlignment = UITextAlignmentRight;
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    [_host release];
    [_port release];
    [_password release];
    [_button release];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

// yuchbox method start here
- (IBAction)toNextView:(id)sender
{
    //[self dismissModalViewControllerAnimated:YES];
    UIView *superview = self.view.superview;
    [superview bringSubviewToFront:[superview.subviews objectAtIndex:0]];
}

- (IBAction)touchBackgroundInSide:(UIButton *)button
{
    [_currentEditTextField resignFirstResponder];
}

#pragma mark - 
#pragma UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    _currentEditTextField = textField;
    return YES;
}

#pragma mark -
#pragma Event invoke
- (void)eventInvoke:(DataSourceEvent)eventCode info:(id)info
{
//    NSLog(@"spring event invoke! %d", eventCode);
    switch (eventCode) {
        case DSEventSBLoginSuccessful: {
            // set the state image
            [self setState:ConnectStateConneted];
            
            // Account info
            Account *account = [[Account alloc] init];
            [Account retrieveAccount:IVAN_DB account:account withHost:_host.text withPort:[_port.text intValue] withPassword:_password.text];

            if (0 == account.uid) {
                account.host        = _host.text;
                account.port        = [_port.text intValue];
                account.password    = _password.text;
            }
            
            account.timestamp   = [[NSDate dateWithTimeIntervalSinceNow:0] timeIntervalSince1970];
            account.isAutoLogin = YES;
            
            Account *accountSession     = [YuchBoxAppDelegate shareAccount];
            accountSession.host         = account.host;
            accountSession.port         = account.port;
            accountSession.password     = account.password;
            accountSession.timestamp    = account.timestamp;
            accountSession.isAutoLogin  = account.isAutoLogin;
            
            [accountSession save:IVAN_DB];
            [account release];
//            [account release];
//            [(YuchBoxAppDelegate *)[YuchBoxAppDelegate shareAppDelegate] setupMainView];
            
            _connectRetryTimes = 0;
            break;
        }
        case DSEventSBLoginFailed:
            [self setState:ConnectStateDisconnet];
            break;
        case DSEventSBReady:
            // the base network is ready, send the login message
            break;
        case DSEventNetErrorOperationCannotBeCompleted: 
        case DSEventErrorFromNet:
            TTLOG_ERROR(@"DSEventErrorFromNet!");
        case DSEventNetErrorUnknown: {
            [self setState:ConnectStateDisconnet];
            TTLOG_ERROR(@"Unknown net error!");

            // reconnect
            if (_connectRetryTimes++ < MAX_RETRY_TIMES) {
                TTLOGF_INFO(@"reconnect try times %d", _connectRetryTimes);
                [DATA_SOURCE performSelectorOnMainThread:@selector(connectAndLogin) withObject:nil waitUntilDone:YES];
            }
            break;
        }
        default:
            break;
    }
}
@end
